import { REQUEST_CODE, REQUEST_MSG } from '@/utils/enums';
import type { Response } from '@/utils/types';
import axios from 'axios';
import { Duplex, Stream } from 'stream';

/**
 * @description: 统一返回体
 * @author: 白雾茫茫丶
 */
export const responseMessage = <T = any>(
  data,
  msg: string = REQUEST_MSG.SUCCESS,
  code: number = REQUEST_CODE.SUCCESS,
): Response<T> => {
  return { data, msg, code };
};

export function updateValue(obj, pathArray, newValue) {
  // 拆分路径为数组
  const newObj = obj;
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  // const [_, ...pathArray] = path.split('.');

  // 初始化当前对象为 obj
  let currentObj = newObj;

  // 遍历路径数组
  for (let i = 0; i < pathArray.length - 1; i++) {
    // 如果当前属性不存在，则创建一个空对象
    currentObj[pathArray[i]] = currentObj[pathArray[i]] || {};
    // 更新当前对象为当前属性的值
    currentObj = currentObj[pathArray[i]];
  }

  // 更新路径的最后一个属性的值为新值
  currentObj[pathArray[pathArray.length - 1]] = newValue;
}

// #utils/fs
// Stream 转 Buffer
export const streamToBuffer: (stream: Stream) => Promise<Buffer> = (stream) =>
  new Promise((resolve, reject) => {
    const buffers = [];
    stream.on('error', reject);
    stream.on('data', (data) => buffers.push(data));
    stream.on('end', () => resolve(Buffer.concat(buffers)));
  });

// Buffer 转 Stream
export const bufferToStream = (buffer) => {
  const stream = new Duplex();
  stream.push(buffer);
  stream.push(null);
  return stream;
};
export const generatePdfByUrl = async (previewurl) => {
  const url =
    process.env.NODE_ENV === 'development'
      ? 'http://localhost:3009/generatePdfByUrl'
      : 'http://pdf-generator:3009/generatePdfByUrl';

  const res = await axios.post(
    url,
    {
      url: previewurl,
    },
    { responseType: 'arraybuffer' },
  );
  return res.data;
};

export const generatePdf = async (htmlString) => {
  const url =
    process.env.NODE_ENV === 'development'
      ? 'http://localhost:3009/generatePdf'
      : 'http://pdf-generator:3009/generatePdf';
  try {
    const res = await axios.post(
      url,
      {
        htmlString: htmlString,
      },
      { responseType: 'arraybuffer' },
    );
    return res.data;
  } catch (e) {
    return '';
  }
};
export const generatePdf2 = async (htmlString) => {
  const url = 'https://www.jianli101.com/v14/resume/generatePdf';
  const res = await axios.post(
    url,
    {
      htmlString: htmlString,
    },
    { responseType: 'arraybuffer' },
  );
  return res.data;
};
